﻿using System;
using System.Configuration;
using System.IO;
using Controllers;

namespace Web
{
    public partial class FileDownload : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string fileId = Request.QueryString["fileId"];
            FileController fc=new FileController();
            Controllers.File f = fc.GetFile(int.Parse(fileId));
            string fileName =f.Name+DateTime.Today.ToString("yyyy-MM-dd")+"."+f.Type;//客户端保存的文件名
            fileName = Server.UrlEncode(fileName);
            string filePath = "PersonalFolder\\";
            if(f.FileClass==1)
            { filePath = "ShareFolder\\"; }
            else if (f.FileClass == 2)
            { filePath = "NoticeFolder\\"; }
            string httpPath =filePath + f.RealName;
            filePath = Server.MapPath(filePath+f.RealName);//路径

            EmpBasicInfo ebi = Session["ebi"] as EmpBasicInfo;
            var v = new FileReadLog();
            v.FileId = int.Parse(fileId);
            v.ReaderId = ebi.Id;
            v.ActionId = 0;
            v.ReadDate = DateTime.Now;
            ApolloOaDataContext ctx = new ApolloOaDataContext(ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString);
            ctx.FileReadLogs.InsertOnSubmit(v);
            ctx.SubmitChanges();

            if(f.Size>5000000)
            {
                Response.Redirect(httpPath);
            }
            else
            {
                FileInfo fileInfo = new FileInfo(filePath);
                Response.Clear();
                Response.ClearContent();
                Response.ClearHeaders();
                Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
                Response.AddHeader("Content-Length", fileInfo.Length.ToString());
                Response.AddHeader("Content-Transfer-Encoding", "binary");
                Response.ContentType = "application/octet-stream";
                Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
                Response.WriteFile(fileInfo.FullName);
                Response.Flush();
            }
            Response.End();
        }
    }
}